<template>
  <div>
    <div style="margin-bottom: 10px">

      <el-card>
        <el-input style="width: 200px; margin-right: 10px" v-model="params.name"  placeholder="请输入书名查询"></el-input>
        <el-input style="width: 200px; margin-right: 10px" v-model="params.author"  placeholder="请输入作者查询"></el-input>
        <el-button type="primary" @click="Search">查询</el-button>
        <el-button type="warning" @click="reset()">重置</el-button>
      </el-card>

    </div>

    <div>
      <el-card>
        <el-button size="small" type="primary" @click="add()">新增</el-button>
        <el-button size="small" type="danger" @click="delBatch()">批量删除</el-button>
      </el-card>
    </div>

    <div style="margin-top: 10px">
      <el-card>
        <el-table :data="tableData" style="width: 100%" ref="table" @selection-change="handleSelectionChange" :row-key="getRowKeys">
          <el-table-column ref="table" type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
          <el-table-column prop="id" label="ID" width="70"></el-table-column>
          <el-table-column prop="name" label="名称" width="110px" ></el-table-column>
          <el-table-column prop="price" label="价格" ></el-table-column>
          <el-table-column prop="num" label="数量" ></el-table-column>
          <el-table-column prop="author" label="作者" ></el-table-column>
          <el-table-column prop="press" label="出版社"></el-table-column>
          <el-table-column prop="typeName" label="图书分类"></el-table-column>
          <el-table-column label="图书封面">
            <template v-slot="scope">
              <el-image
                  style="width: 40px; height: 40px; border-radius: 50%"
                  :src="'http://localhost:9090/api/files/' + scope.row.img"
                  v-if="scope.row.img"
                  :preview-src-list="['http://localhost:9090/api/files/' + scope.row.img]">
              </el-image>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" >
            <template slot-scope="scope">
              <!-- <el-button type="primary" @click="down(scope.row.img)">下载</el-button>-->
              <el-button type="primary" @click="edit(scope.row)" v-if="user.role === 'ADMIN'">编辑</el-button>
              <el-button type="primary" @click="borrow(scope.row)" v-if="user.role !== 'ADMIN'">借阅</el-button>
              <el-button type="danger" @click="del(scope.row.id)" v-if="user.role === 'ADMIN'">删除</el-button>
            </template>

          </el-table-column>
        </el-table>

        <div style="margin-top: 20px">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="params.pageNum"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="params.pageSize"
              layout="total, sizes, prev, pager, next"
              :total="total">
          </el-pagination>
        </div>

      </el-card>
    </div>

    <div>
      <el-dialog title="请填写图书信息" :visible.sync="dialogFormVisible" width="33%">
        <el-form :model="form">
          <el-form-item label="名称" label-width="15%">
            <el-input v-model="form.name" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="价格" label-width="15%">
            <el-input v-model="form.price" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="数量" label-width="15%">
            <el-input v-model="form.num" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="作者" label-width="15%">
            <el-input v-model="form.author" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="出版社" label-width="15%">
            <el-input v-model="form.press" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="图书分类" label-width="15%">
            <el-select v-model="form.typeId" placeholder="请选择" style="width: 90%">
              <el-option v-for="item in typeObjs" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书封面" label-width="20%">
            <el-upload ref="upload" action="http://localhost:9090/api/files/upload"
                       list-type="picture"
                       :on-success="successUpload">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      //自定义一个params的变量
      params: {
        name: '',
        author: '',
        pageNum: 1,
        pageSize: 5
      },
      tableData: [],
      total:0,
      dialogFormVisible: false,
      form: {},
      multipleSelection: [],
      typeObjs: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  },
  // 页面加载的时候，在created里面做的一些事情
  created() {
      this.Search();
    this.findTypes();
  },
  //会定义一些触发的事件方法
  methods:{
    findTypes() {
      request.get("/type").then(res => {
        if (res.code === '200') {
          this.typeObjs = res.data;
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // down(flag) {
    //   location.href = 'http://localhost:9090/api/files/' + flag
    // },
    successUpload(res) {
      this.form.img = res.data;
    },
    add() {
      this.dialogFormVisible = true;
      this.form = {};
      // 清空已选择的文件
      this.$refs.upload.clearFiles();
    },
    edit(obj) {
      this.form = obj;
      this.dialogFormVisible = true;
    },
    del(id) {
      this.$confirm('确定要删除该条记录吗?', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete("/book/" + id).then(res => {
          if (res.code === '200') {
            this.$message.success("删除成功")
            this.Search();
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        // 取消删除操作
      });
    },
    submit() {
      request.post("/book", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("操作成功")
          this.dialogFormVisible = false;
          this.Search();
          this.form.img = ''
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    Search(){
      request.get('/book/search',{
        params: this.params
      }).then(res =>{
        if (res.code === '200'){
            this.tableData = res.data.list
            this.total = res.data.total
            // this.$message.success("操作成功")
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    reset(){
      this.params = {
        name: '',
        author: '',
        pageNum: 1,
        pageSize: 5
      }
      this.Search()
    },
    handleSizeChange(pageSize){
      this.params.pageSize = pageSize
      this.Search()
    },
    handleCurrentChange(pageNum){
      this.params.pageNum = pageNum
      this.Search();
    },
    delBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请勾选您要删除的项")
        return
      }
      this.$confirm('确定要删除该条记录吗?', '确认删除', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}).then(() => {
        request.put("/book/delBatch", this.multipleSelection).then(res => {
          if (res.code === '200') {
            this.$message.success("批量删除成功")
            this.Search()
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        // 取消删除操作
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getRowKeys(row) {
      return row.id;
    },
    borrow(row) {
      let param = {bookId: row.id, userId: this.user.id}
      request.post("/borrow", param).then(res => {
        if (res.code === '200') {
          this.$message.success("借阅成功")
          this.Search()
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  }
}
</script>
<style scoped>

</style>